const { prisma } = require('../config/prisma');

/**
 * 为用户端创建测试用户和相关数据
 * 包含完整的业务场景测试数据
 */
async function createClientTestUsers() {
  try {
    console.log('🚀 开始为用户端创建测试用户...');

    // 测试用户数据
    const testUsers = [
      {
        openid: 'test_client_user_001',
        nickname: '张老板',
        avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
        phone_number: '13800138001',
        wechat_id: 'zhang_boss_001',
        status: 'active',
        chat_banned: false,
        publishing_credits: 10,
        chat_credits: 50,
        contact_view_credits: 20
      },
      {
        openid: 'test_client_user_002',
        nickname: '李经理',
        avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj4FeGiaEWqhPLuuZ7VV7Q5AE9TYkBGEjdgbU1Y4zOHxZGMDHPKxiaOV6XrAd6bD8TvxHGJ3r6i9YA/132',
        phone_number: '13800138002',
        wechat_id: 'li_manager_002',
        status: 'active',
        chat_banned: false,
        publishing_credits: 5,
        chat_credits: 30,
        contact_view_credits: 15
      },
      {
        openid: 'test_client_user_003',
        nickname: '王总',
        avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKEAcECOqMbaSG4QdxOVcpDvuGnOyiaahqyaE5RnG8Km9hxIWj7IvqOPRq7LMc7YN1xKPBuaZhM6Bg/132',
        phone_number: '13800138003',
        wechat_id: 'wang_ceo_003',
        status: 'active',
        chat_banned: false,
        publishing_credits: 15,
        chat_credits: 80,
        contact_view_credits: 30
      },
      {
        openid: 'test_client_user_004',
        nickname: '陈会计',
        avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/ajNVdqHZLLDicLcuVVlucHFfY2qWgBVL8WQia4R7x0Lr5O8nOhT3R2xdVtpBKJZPIq5JaibgLYhGJtBJGNiaZfOO4w/132',
        phone_number: '13800138004',
        wechat_id: 'chen_accountant_004',
        status: 'active',
        chat_banned: false,
        publishing_credits: 3,
        chat_credits: 20,
        contact_view_credits: 10
      },
      {
        openid: 'test_client_user_005',
        nickname: '刘代理',
        avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKO1hNc5v3HNNLnS6dRzBbZHnKb8NMqYGhJQ8kOHPnxFvV0U8gJ1m2nQvLnkC9xHnMQU5v0EZrVlg/132',
        phone_number: '13800138005',
        wechat_id: 'liu_agent_005',
        status: 'inactive', // 未激活用户，用于测试激活流程
        chat_banned: false,
        publishing_credits: 0,
        chat_credits: 0,
        contact_view_credits: 0
      },
      {
        openid: 'test_client_user_006',
        nickname: '马老板',
        avatar_url: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
        phone_number: null, // 未设置手机号
        wechat_id: 'ma_boss_006',
        status: 'active',
        chat_banned: true, // 被禁言用户，测试聊天功能
        publishing_credits: 8,
        chat_credits: 0,
        contact_view_credits: 5
      }
    ];

    console.log('📝 创建测试用户...');
    const createdUsers = [];
    
    for (const userData of testUsers) {
      try {
        // 检查用户是否已存在
        const existingUser = await prisma.users.findUnique({
          where: { openid: userData.openid }
        });

        if (existingUser) {
          console.log(`⚠️ 用户 ${userData.nickname} 已存在，更新数据...`);
          const updatedUser = await prisma.users.update({
            where: { openid: userData.openid },
            data: userData
          });
          createdUsers.push(updatedUser);
        } else {
          const newUser = await prisma.users.create({
            data: userData
          });
          createdUsers.push(newUser);
          console.log(`✅ 创建用户: ${userData.nickname} (ID: ${newUser.id})`);
        }
      } catch (error) {
        console.error(`❌ 创建用户 ${userData.nickname} 失败:`, error);
      }
    }

    // 创建邀请关系
    console.log('📝 创建邀请关系...');
    if (createdUsers.length >= 3) {
      try {
        // 张老板邀请了李经理
        await prisma.invitations.upsert({
          where: { invitee_user_id: createdUsers[1].id },
          create: {
            inviter_user_id: createdUsers[0].id,
            invitee_user_id: createdUsers[1].id,
            reward_type: 'activation',
            status: 'claimed'
          },
          update: {
            inviter_user_id: createdUsers[0].id,
            reward_type: 'activation',
            status: 'claimed'
          }
        });

        // 李经理邀请了王总
        await prisma.invitations.upsert({
          where: { invitee_user_id: createdUsers[2].id },
          create: {
            inviter_user_id: createdUsers[1].id,
            invitee_user_id: createdUsers[2].id,
            reward_type: 'credits',
            reward_value: 10,
            status: 'claimed'
          },
          update: {
            inviter_user_id: createdUsers[1].id,
            reward_type: 'credits',
            reward_value: 10,
            status: 'claimed'
          }
        });

        console.log('✅ 邀请关系创建完成');
      } catch (error) {
        console.error('❌ 创建邀请关系失败:', error);
      }
    }

    // 创建测试挂牌信息
    console.log('📝 创建测试挂牌信息...');
    const testListings = [
      {
        user_id: createdUsers[0].id,
        listing_type: 'COMPANY',
        company_name: '北京科技有限公司',
        status: 'ON_SALE',
        price: 150000.00,
        is_negotiable: true,
        registration_province: '北京市',
        registration_city: '朝阳区',
        establishment_date: new Date('2020-05-15'),
        registered_capital_range: 'FROM_100K_TO_500K',
        paid_in_status: 'PAID',
        company_type: 'NORMAL',
        tax_status: 'GENERAL_TAXPAYER',
        tax_grade: 'GRADE_A',
        bank_account_status: 'OPENED',
        has_trademark: true,
        has_patent: false,
        has_software_copyright: true,
        has_license_plate: true,
        has_social_security: true,
        bank_flow: '月流水100-200万',
        has_bidding_history: true,
        description: '转让北京科技公司，注册资本100万已实缴，有商标专利，银行流水良好，适合科技类业务',
        audit_status: 'APPROVED'
      },
      {
        user_id: createdUsers[1].id,
        listing_type: 'INDIVIDUAL',
        company_name: '李氏餐饮个体户',
        status: 'ON_SALE',
        price: 50000.00,
        is_negotiable: false,
        registration_province: '上海市',
        registration_city: '浦东新区',
        establishment_date: new Date('2021-03-10'),
        registered_capital_range: null,
        paid_in_status: null,
        company_type: null,
        tax_status: 'SMALL_SCALE',
        tax_grade: 'GRADE_B',
        bank_account_status: 'OPENED',
        has_trademark: false,
        has_patent: false,
        has_software_copyright: false,
        has_license_plate: false,
        has_social_security: false,
        bank_flow: '月流水20-50万',
        has_bidding_history: false,
        description: '转让上海餐饮个体户，小规模纳税人，适合餐饮行业',
        audit_status: 'APPROVED'
      },
      {
        user_id: createdUsers[2].id,
        listing_type: 'ACCOUNTING',
        company_name: '王氏代账服务',
        status: 'ON_SALE',
        price: 80000.00,
        is_negotiable: true,
        registration_province: '广东省',
        registration_city: '深圳市',
        establishment_date: new Date('2019-08-20'),
        registered_capital_range: 'FROM_500K_TO_1M',
        paid_in_status: 'UNCERTAIN',
        company_type: 'NORMAL',
        tax_status: 'GENERAL_TAXPAYER',
        tax_grade: 'GRADE_A',
        bank_account_status: 'OPENED',
        has_trademark: false,
        has_patent: false,
        has_software_copyright: false,
        has_license_plate: true,
        has_social_security: true,
        bank_flow: '月流水50-100万',
        has_bidding_history: false,
        description: '转让深圳代账公司，客户资源丰富，有稳定收入来源',
        audit_status: 'PENDING'
      }
    ];

    for (const listingData of testListings) {
      try {
        await prisma.listings.create({
          data: listingData
        });
        console.log(`✅ 创建挂牌: ${listingData.company_name}`);
      } catch (error) {
        console.error(`❌ 创建挂牌 ${listingData.company_name} 失败:`, error);
      }
    }

    // 创建测试群组（如果不存在）
    console.log('📝 创建测试群组...');
    const testGroups = [
      { id: 1, group_name: '全国接单总群', description: '全国范围内的接单信息交流群', group_type: 'group' },
      { id: 10, group_name: '北京同行群', description: '北京地区同行交流群', group_type: 'group' },
      { id: 11, group_name: '上海同行群', description: '上海地区同行交流群', group_type: 'group' },
      { id: 12, group_name: '深圳同行群', description: '深圳地区同行交流群', group_type: 'group' }
    ];

    for (const groupData of testGroups) {
      try {
        await prisma.chat_groups.upsert({
          where: { id: groupData.id },
          create: groupData,
          update: {
            group_name: groupData.group_name,
            description: groupData.description
          }
        });
        console.log(`✅ 群组: ${groupData.group_name}`);
      } catch (error) {
        console.error(`❌ 创建群组 ${groupData.group_name} 失败:`, error);
      }
    }

    // 将用户加入群组
    console.log('📝 添加用户到群组...');
    const groupMemberships = [
      // 全国总群 - 所有用户都加入
      { group_id: 1, user_id: createdUsers[0].id, role: 'admin' },
      { group_id: 1, user_id: createdUsers[1].id, role: 'member' },
      { group_id: 1, user_id: createdUsers[2].id, role: 'member' },
      { group_id: 1, user_id: createdUsers[3].id, role: 'member' },
      { group_id: 1, user_id: createdUsers[4].id, role: 'member' },
      { group_id: 1, user_id: createdUsers[5].id, role: 'member' },
      // 地区群组
      { group_id: 10, user_id: createdUsers[0].id, role: 'admin' },
      { group_id: 11, user_id: createdUsers[1].id, role: 'admin' },
      { group_id: 12, user_id: createdUsers[2].id, role: 'admin' }
    ];

    for (const membership of groupMemberships) {
      try {
        await prisma.group_members.upsert({
          where: {
            group_id_user_id: {
              group_id: membership.group_id,
              user_id: membership.user_id
            }
          },
          create: membership,
          update: { role: membership.role }
        });
      } catch (error) {
        console.error(`❌ 添加用户到群组失败:`, error);
      }
    }
    console.log('✅ 用户群组关系创建完成');

    // 创建测试消息
    console.log('📝 创建测试消息...');
    const testMessages = [
      {
        group_id: 1,
        sender_id: createdUsers[0].id,
        message_type: 'text',
        content: '大家好！我这里有一家北京的科技公司要转让，有需要的朋友可以私聊我'
      },
      {
        group_id: 1,
        sender_id: createdUsers[1].id,
        message_type: 'text',
        content: '上海地区有餐饮个体户转让，价格优惠，详情私聊'
      },
      {
        group_id: 1,
        sender_id: createdUsers[2].id,
        message_type: 'text',
        content: '收购深圳代账公司，有合适资源的朋友联系我'
      },
      {
        group_id: 1,
        sender_id: createdUsers[3].id,
        message_type: 'text',
        content: '专业代账服务，为各类企业提供财税咨询'
      }
    ];

    for (const messageData of testMessages) {
      try {
        await prisma.messages.create({
          data: messageData
        });
      } catch (error) {
        console.error('❌ 创建消息失败:', error);
      }
    }
    console.log('✅ 测试消息创建完成');

    console.log('\n🎉 用户端测试数据创建完成！');
    console.log('📊 数据统计:');
    
    // 统计数据
    const userCount = await prisma.users.count();
    const listingCount = await prisma.listings.count();
    const groupCount = await prisma.chat_groups.count();
    const messageCount = await prisma.messages.count();
    
    console.log(`   - 用户数量: ${userCount}`);
    console.log(`   - 挂牌信息: ${listingCount}`);
    console.log(`   - 群组数量: ${groupCount}`);
    console.log(`   - 消息数量: ${messageCount}`);

    console.log('\n👥 测试用户列表:');
    for (const user of createdUsers) {
      console.log(`   - ${user.nickname} (${user.openid}) - ${user.status === 'active' ? '已激活' : '未激活'}`);
    }

    return createdUsers;

  } catch (error) {
    console.error('❌ 创建用户端测试数据失败:', error);
    throw error;
  }
}

/**
 * 清理测试用户数据
 */
async function cleanupClientTestUsers() {
  try {
    console.log('🗑️ 开始清理用户端测试数据...');

    const testUserOpenids = [
      'test_client_user_001',
      'test_client_user_002', 
      'test_client_user_003',
      'test_client_user_004',
      'test_client_user_005',
      'test_client_user_006'
    ];

    // 删除测试用户（会级联删除相关数据）
    const deleteResult = await prisma.users.deleteMany({
      where: {
        openid: {
          in: testUserOpenids
        }
      }
    });

    console.log(`✅ 已删除 ${deleteResult.count} 个测试用户及相关数据`);

  } catch (error) {
    console.error('❌ 清理测试数据失败:', error);
    throw error;
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  const action = process.argv[2];
  
  if (action === 'cleanup') {
    cleanupClientTestUsers()
      .then(() => {
        console.log('🎉 测试数据清理完成！');
        process.exit(0);
      })
      .catch(() => process.exit(1));
  } else {
    createClientTestUsers()
      .then(() => {
        console.log('🎉 用户端测试数据创建完成！');
        process.exit(0);
      })
      .catch(() => process.exit(1));
  }
}

module.exports = {
  createClientTestUsers,
  cleanupClientTestUsers
};